package com.joint.cloud.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.stereotype.Component;

import java.beans.Introspector;

@Component
public class SpringUtil implements ApplicationContextAware {

    private static Logger logger = LoggerFactory.getLogger(SpringUtil.class);

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContextParam) throws BeansException {
        applicationContext = applicationContextParam;
    }

    public static Object getObject(String id) {
        Object object = null;
        object = applicationContext.getBean(id);
        return object;
    }

    public static <T> T getObject(Class<T> tClass) {
        return applicationContext.getBean(tClass);
    }

    public static Object getBean(String tClass) {
        return applicationContext.getBean(tClass);
    }

    public static <T> T getBean(Class<T> tClass) {
        return applicationContext.getBean(tClass);
    }

    public static <T> T getBean(String beanId, Class<T> requiredType) {
        if (applicationContext == null) {
            logger.warn("Spring context has not bean initilaized!");
            return null;
        }
        return applicationContext.getBean(beanId, requiredType);
    }

    public static String toBeanName(String simpleClassName) {

        //参照Spring Context中AnnotationBeanNameGenerator的方法
        return Introspector.decapitalize(simpleClassName);
//        return simpleClassName.substring(0, 1).toLowerCase()
//                + simpleClassName.substring(1);


    }
    public static void publishEvent(ApplicationEvent event){
        applicationContext.publishEvent(event);
    }
}